from datetime import datetime
from django.db import models
from django.conf import settings
from django.contrib.sites.models import Site
from podcasts.managers import PodcastManager, EpisodeManager

class Podcast(models.Model):
	"A Podcast acts as a container for a series of episodes."
	# TODO: Add author link field?
	# http://www.apple.com/itunes/store/podcaststechspecs.html
	# http://www.mypodcast.com/help-Submitting_your_podcast_-59.html
	
	on_site = PodcastManager()
	objects = models.Manager()
	site = models.ForeignKey(Site, editable=False, default=settings.SITE_ID)
	
	# Basic info
	title = models.CharField(max_length=100)
	description = models.TextField(blank=True, help_text=u'Describe the theme of all episodes in this podcast series.')	

	# Optional info
	author = models.CharField(blank=True, max_length=100,
		help_text=u'Enter the name of the person or organization publishing this podcast series.')
	copyright = models.CharField(blank=True, max_length=100,
		help_text=u'Brief copyright statement for this podcast series.	Use &amp;#xA9; in place of the copyright (c) symbol. ') 
	image = models.ImageField(blank=True, upload_to=u'podcasts', help_text=u'Images should be 300 pixels square.')
	use_image = models.BooleanField(default=False, help_text=u"Check this box if you want to use the image above.")
	link = models.URLField(blank=True, verify_exists=True,
		help_text=u'Enter your website URL, or a URL to a page describing this podcast series.  Leave blank to use default (recommended).')

	# iTunes
	category = models.CharField(blank=True, max_length=25, help_text=u'The iTunes category this podcast belongs to.')
	keywords = models.CharField(blank=True, max_length=100,
		help_text=u'Enter comma-seperated keywords that describe the content of this podcast series.  '
		'Note that iTunes will only use the first 12 words.')
	explicit = models.BooleanField(u'Contains explicit content', default=False)
	
	# Advanced info
	enable = models.BooleanField(u'Enable this podcast', default=True,
		help_text=u'Uncheck this box if you do not wish to publish this podcast series at this time.')
	language = models.CharField(blank=True, max_length=10, default=u"en-us",
		help_text=u'Enter the language code for this podcast series.  Use "en-us" for English (default).')
	slug = models.SlugField(prepopulate_from=("title",), max_length=25)
	
	def __unicode__(self):
		return self.title
	
	@property
	def episodes(self):
		"Returns all the published episodes in this podcast."
		return Episode.on_site.published().filter(podcast=self)
	
	@models.permalink
	def get_absolute_url(self):
		return ('podcast_detail', (), {'slug':self.slug})
	
	@models.permalink	
	def get_feed_url(self):
		return ('podcast_feed', (), {'url': 'episodes/%s' % self.slug})
	
	class Meta:
		ordering = ('title',)
		unique_together = (('site', 'slug'),)
	
	class Admin:
		list_display = ('title', 'enable')
		list_filter = ('enable', 'category')
		search_fields = ('title', 'keywords', 'description')
		ordering = ('title',)
		fields = (
			('Basic info', {
				'fields': ('title', 'description',)
			}),
			('Optional info', {
				'fields' : ('author', 'copyright', 'image', 'use_image', 'link')
			}),
			('iTunes info', {
				'classes': 'collapse',
				'fields' : ('category', 'keywords', 'explicit'),
			}),
			('Advanced', {
				'classes': 'collapse',
				'fields' : ('enable', 'language', 'slug'),
			}),			
		)
		
		
class Episode(models.Model):
	"An Episode of a Podcast (the audio file and any meta data relating to it)"
	on_site = EpisodeManager()
	objects = models.Manager()
	podcast = models.ForeignKey(Podcast, help_text=u'Select the podcast series this episode belongs to.')
	
	title = models.CharField(u"Episode title", max_length=100)
	audio_file = models.FileField(upload_to='podcasts/%Y/%b/%d',
		help_text=u'Select the audio file for this episode.<br />'
		'<strong>Allowed file formats:</strong> mp3, m4a, mp4')
	
	image = models.ImageField(upload_to="podcasts/%Y/%b/%d/images", blank=True,
		help_text=u'Select an image to be displayed for this episode.')
	use_image = models.BooleanField(default=False,
		help_text=u'Check this box to have the image displayed on the website.')
	
	description = models.TextField(u'Episode description', blank=True,
		help_text=u'Will default to Podcast description if left blank.')
	date = models.DateTimeField(u"Publish date", default=datetime.now,
		help_text=u'Episodes are published in chronological order.  You may future-date episodes.')
	
	author_name = models.CharField(blank=True, max_length=100,
		help_text=u'Defaults to author of the Podcast, if left blank.')
	author_link = models.URLField(blank=True, verify_exists=True,
		help_text=u'Link back to a profile page of the author.')
	author_email = models.EmailField(blank=True,
		help_text=u'You can optionally incude the author\'s email address.')
	copyright = models.CharField(blank=True, max_length=100,
		help_text=u'Defaults to Podcast copyright if left blank.')
	duration = models.CharField(blank=True, max_length=10,
		help_text=u'iTunes will automatically determine the duration, but to have it appear on the website you must enter it here.<br />'
		'<strong>Format: HH:MM:SS.</strong>')
	link = models.URLField(blank=True, verify_exists=True,
		help_text=u'Link back to a page with details about this podcast.  Leave blank to use default (recommended).')
	category = models.CharField(blank=True, max_length=25,
		help_text=u'Defaults to Podcast category if left blank.')
	keywords = models.CharField(blank=True, max_length=100,
		help_text=u'Defaults to Podcast keywords if left blank.')

	def __unicode__(self):
		return self.title

	@models.permalink
	def get_absolute_url(self):
		return ('episode_detail', (), {'object_id':self.id})

	def save(self):
		# Fill out a bunch of properties if left blank. What a hack.
		for attr in "description link copyright category keywords".split(" "):
			if getattr(self, attr, '') == '':
				setattr(self, attr, getattr(self.podcast, attr))
		if not self.author_name:
			self.author_name = self.podcast.author
		super(Episode, self).save()

	class Meta:
		ordering = ('date', 'title')

	class Admin:
		list_display = ('title', 'duration', 'podcast', 'date',)
		list_filter = ('date', 'podcast')
		search_fields = ('title', 'keywords', 'description')
		ordering = ('date', 'title')
